package com.example.concurrentprogramming8016.future.forkjoin.arraysum;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author liyanhao
 * @Date 2023-01-08 8:46
 */
public class MutilThreads2 {
    private static final long NUM = 1000000;

    public static long sumCount(int[] arr, ExecutorService executorService,int threadNum) throws ExecutionException, InterruptedException {
        long result = 0;
        SumTask[] sumTask = new SumTask[threadNum];
        Future<Long>[] futures = new Future[threadNum];
        int avg = arr.length / threadNum;
        for (int i = 0; i < threadNum; i++) {
            sumTask[i] = new SumTask(arr, i * avg, (i + 1) * avg);
            futures[i] = executorService.submit(sumTask[i]);
        }
        for (int i = 0; i < futures.length; i++) {
            result += futures[i].get();
            System.out.println("result:" + result);
        }
        return result;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int[] arr = buildRandomIntArray(10000000);
        int threadNum = 10;
        ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
        long sum = sumCount(arr, threadPool, threadNum);
        ExecutorService threadPool1 = Executors.newFixedThreadPool(threadNum);
        long sum1 = SumMultiThreads.sum(arr, threadPool1);
        threadPool.shutdown();
        System.out.println(sum);
        System.out.println(sum1);
        threadPool1.shutdown();
    }

    public static int[] buildRandomIntArray(int size){
        int[] arrayToCalculateSumOf = new int[size];
        Random generator = new Random();
        for (int i = 0; i < arrayToCalculateSumOf.length; i++) {
            arrayToCalculateSumOf[i] = generator.nextInt(1000);
        }
        return arrayToCalculateSumOf;
    }

}

class SumTask implements Callable<Long> {
    private int[] arr;
    private int start;
    private int end;

    public SumTask(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    @Override
    public Long call() throws Exception {
        return sumArrUtils.SumArr(arr, start, end);
    }
}

class sumArrUtils {
    public static long SumArr(int[] arr, long start, long end) {
        long result = 0;
        for (int i = (int) start; i < end; i++) {
            result += arr[i];
        }
        return result;
    }
}
